package cn.zhentao.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 游戏会话实体类 - 管理游戏状态的持续性
 */
@Data
public class GameSession {
    
    /**
     * 会话ID
     */
    private String sessionId;
    
    /**
     * 用户ID
     */
    private Long userId;
    
    /**
     * 游戏类型
     */
    private String gameType;
    
    /**
     * 游戏状态
     */
    private GameState gameState;
    
    /**
     * 当前分数
     */
    private Integer score;
    
    /**
     * 连胜次数
     */
    private Integer winStreak;
    
    /**
     * 游戏等级
     */
    private Integer level;
    
    /**
     * 当前题目/挑战
     */
    private String currentChallenge;
    
    /**
     * 正确答案（用于验证）
     */
    private String correctAnswer;
    
    /**
     * 游戏历史记录
     */
    private List<GameRecord> gameHistory;
    
    /**
     * 游戏配置
     */
    private GameConfig gameConfig;
    
    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;
    
    /**
     * 最后更新时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updateTime;
    
    /**
     * 游戏状态枚举
     */
    public enum GameState {
        WAITING("等待开始"),
        PLAYING("游戏中"),
        PAUSED("暂停"),
        FINISHED("已结束"),
        TIMEOUT("超时");
        
        private final String description;
        
        GameState(String description) {
            this.description = description;
        }
        
        public String getDescription() {
            return description;
        }
    }
    
    /**
     * 游戏记录内部类
     */
    @Data
    public static class GameRecord {
        private String question;
        private String userAnswer;
        private String correctAnswer;
        private boolean isCorrect;
        private Integer pointsEarned;
        private LocalDateTime answerTime;
        private Long responseTimeMs;
    }
    
    /**
     * 游戏配置内部类
     */
    @Data
    public static class GameConfig {
        private Integer maxQuestions;
        private Integer timeLimit; // 秒
        private String difficulty;
        private boolean enableHints;
        private Integer hintsRemaining;
        private Integer pointsPerCorrect;
        private Integer bonusMultiplier;
    }
    
    /**
     * 构造函数
     */
    public GameSession() {
        this.gameHistory = new ArrayList<>();
        this.score = 0;
        this.winStreak = 0;
        this.level = 1;
        this.gameState = GameState.WAITING;
        this.createTime = LocalDateTime.now();
        this.updateTime = LocalDateTime.now();
        this.gameConfig = new GameConfig();
        initDefaultConfig();
    }
    
    /**
     * 初始化默认配置
     */
    private void initDefaultConfig() {
        gameConfig.setMaxQuestions(10);
        gameConfig.setTimeLimit(60);
        gameConfig.setDifficulty("normal");
        gameConfig.setEnableHints(true);
        gameConfig.setHintsRemaining(3);
        gameConfig.setPointsPerCorrect(10);
        gameConfig.setBonusMultiplier(1);
    }
    
    /**
     * 添加游戏记录
     */
    public void addGameRecord(String question, String userAnswer, String correctAnswer, 
                             boolean isCorrect, Long responseTimeMs) {
        GameRecord record = new GameRecord();
        record.setQuestion(question);
        record.setUserAnswer(userAnswer);
        record.setCorrectAnswer(correctAnswer);
        record.setCorrect(isCorrect);
        record.setAnswerTime(LocalDateTime.now());
        record.setResponseTimeMs(responseTimeMs);
        
        // 计算得分
        int points = 0;
        if (isCorrect) {
            points = gameConfig.getPointsPerCorrect() * gameConfig.getBonusMultiplier();
            // 快速回答奖励
            if (responseTimeMs < 10000) { // 10秒内回答
                points += 5;
            }
            // 连胜奖励
            if (winStreak > 0) {
                points += winStreak * 2;
            }
        }
        record.setPointsEarned(points);
        
        gameHistory.add(record);
        updateScore(points, isCorrect);
        this.updateTime = LocalDateTime.now();
    }
    
    /**
     * 更新分数和连胜
     */
    private void updateScore(int points, boolean isCorrect) {
        this.score += points;
        
        if (isCorrect) {
            this.winStreak++;
            // 检查是否升级
            checkLevelUp();
        } else {
            this.winStreak = 0;
        }
    }
    
    /**
     * 检查是否升级
     */
    private void checkLevelUp() {
        int newLevel = (score / 100) + 1; // 每100分升一级
        if (newLevel > this.level) {
            this.level = newLevel;
            // 升级奖励
            this.gameConfig.setBonusMultiplier(this.gameConfig.getBonusMultiplier() + 1);
        }
    }
    
    /**
     * 使用提示
     */
    public boolean useHint() {
        if (gameConfig.isEnableHints() && gameConfig.getHintsRemaining() > 0) {
            gameConfig.setHintsRemaining(gameConfig.getHintsRemaining() - 1);
            return true;
        }
        return false;
    }
    
    /**
     * 获取游戏统计信息
     */
    public GameStats getGameStats() {
        GameStats stats = new GameStats();
        stats.setTotalQuestions(gameHistory.size());
        stats.setCorrectAnswers((int) gameHistory.stream().mapToLong(r -> r.isCorrect() ? 1 : 0).sum());
        stats.setAccuracyRate(stats.getTotalQuestions() > 0 ? 
            (double) stats.getCorrectAnswers() / stats.getTotalQuestions() * 100 : 0);
        stats.setAverageResponseTime(gameHistory.stream()
            .mapToLong(GameRecord::getResponseTimeMs)
            .average().orElse(0));
        return stats;
    }
    
    /**
     * 游戏统计信息内部类
     */
    @Data
    public static class GameStats {
        private Integer totalQuestions;
        private Integer correctAnswers;
        private Double accuracyRate;
        private Double averageResponseTime;
    }
}
